package top.anka1.fxgui;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import top.anka1.ims.*;
import top.anka1.ims.RestaurantManagementSystem.Ingredient;
import top.anka1.ims.RestaurantManagementSystem.Meal;

import java.util.ArrayList;
/**
 * CreateMealController is a controller class for creating meals in the restaurant management system.
 * It handles the interaction between the GUI and the underlying data model.
 * @author Anka
 */
public class CreateMealController {
    private RestaurantGUI restaurantGUI;
    private ObservableList<Ingredient> inventoryIngredients;
    private ObservableList<Ingredient> mealIngredients;
    @FXML
    private TableView<Ingredient> inventoryTable;
    @FXML
    private TableColumn<Ingredient, String> inventoryNameColumn;
    @FXML
    private TableColumn<Ingredient, Double> inventoryPriceColumn;
    @FXML
    private TableView<Ingredient> mealTable;
    @FXML
    private TableColumn<Ingredient, String> mealNameColumn;
    @FXML
    private TableColumn<Ingredient, Double> mealPriceColumn;
    @FXML
    private TextField mealNameTextField;

    public void setData(RestaurantGUI restaurantGUI) {
        this.restaurantGUI = restaurantGUI;
        inventoryNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        inventoryNameColumn.setStyle("-fx-alignment: CENTER;");
        inventoryPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
        inventoryPriceColumn.setStyle("-fx-alignment: CENTER;");
        inventoryPriceColumn.setCellFactory(column -> new javafx.scene.control.cell.TextFieldTableCell<>(
                new javafx.util.converter.DoubleStringConverter() {
                    @Override
                    public String toString(Double value) {
                        if (value == null) return "";
                        return String.format("¥%.2f", value);
                    }
                }
        ));

        mealNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        mealNameColumn.setStyle("-fx-alignment: CENTER;");
        mealPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
        mealPriceColumn.setStyle("-fx-alignment: CENTER;");
        mealPriceColumn.setCellFactory(column -> new javafx.scene.control.cell.TextFieldTableCell<>(
                new javafx.util.converter.DoubleStringConverter() {
                    @Override
                    public String toString(Double value) {
                        if (value == null) return "";
                        return String.format("¥%.2f", value);
                    }
                }
        ));

        ArrayList<Ingredient> ingredientList = new ArrayList<>();
        for (String name : restaurantGUI.getRestaurantService().getIngredientInventory().keySet()) {
            Ingredient ingredient = restaurantGUI.getRestaurantService().getIngredientInventory().get(name);
            ingredientList.add(ingredient);
        }
        inventoryIngredients = FXCollections.observableArrayList(ingredientList);
        inventoryTable.setItems(inventoryIngredients);
    }
    public void showError(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    public void showInformation(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    @FXML
    public void addToMeal() {
        Ingredient selectedIngredient = inventoryTable.getSelectionModel().getSelectedItem();
        try {
            if (selectedIngredient != null) {
                mealIngredients = mealTable.getItems();
                if (!mealIngredients.contains(selectedIngredient)) {
                    mealIngredients.add(selectedIngredient);
                    mealTable.setItems(mealIngredients);
                    inventoryIngredients.remove(selectedIngredient);
                    inventoryTable.setItems(inventoryIngredients);
                } else {
                    showError((Stage) inventoryTable.getScene().getWindow(), "Duplicate Ingredient", "Ingredient already in meal", "Please select a different ingredient.");
                }
            } else {
                showError((Stage) inventoryTable.getScene().getWindow(), "No Selection", "No Ingredient Selected", "Please select an ingredient to add.");
            }
        } catch (Exception e) {
            showError((Stage) inventoryTable.getScene().getWindow(), "Error", "Failed to add ingredient", "Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
    public void removeFromMeal() {
        Ingredient selectedIngredient = mealTable.getSelectionModel().getSelectedItem();
        try {
            if (selectedIngredient != null) {
                ObservableList<Ingredient> mealIngredients = mealTable.getItems();
                mealIngredients.remove(selectedIngredient);
                mealTable.setItems(mealIngredients);
                inventoryIngredients.add(selectedIngredient);
                inventoryTable.setItems(inventoryIngredients);
            } else {
                showError((Stage) mealTable.getScene().getWindow(), "No Selection", "No Ingredient Selected", "Please select an ingredient to remove.");
            }
        } catch (Exception e) {
            showError((Stage) mealTable.getScene().getWindow(), "Error", "Failed to remove ingredient", "Error: " + e.getMessage());
        }
    }
    public void confirmMeal() {
        String mealName = mealNameTextField.getText();
        if (mealName.isEmpty()) {
            showError((Stage) mealNameTextField.getScene().getWindow(), "Input Error", "Meal name cannot be empty", "Please enter a valid meal name.");
            return;
        }
        ArrayList<Ingredient> ingredients = new ArrayList<>(mealTable.getItems());
        if (ingredients.isEmpty()) {
            showError((Stage) mealNameTextField.getScene().getWindow(), "Input Error", "Meal must have at least one ingredient", "Please add ingredients to the meal.");
            return;
        }
        Meal meal = new Meal(mealName);
        for (Ingredient ingredient : ingredients) {
            meal.addIngredient(ingredient);
        }
        restaurantGUI.getRestaurantService().getMeals().add(meal);
        showInformation((Stage) mealNameTextField.getScene().getWindow(), "Success", "Meal Created", "Meal " + mealName + " has been created successfully.");
    }
}
